import urllib.request
import urllib.parse
import os
import time
import ssl

# 目标PDF文件名
pdf_filename = '人工智能对就业市场的影响数据集.pdf'
# 保存路径
save_dir = r'd:\D'
pdf_save_path = os.path.join(save_dir, pdf_filename)

# 用户明确指定的基础URL模板
base_url_template = "https://moor-smile.shec.edu.cn/rest/pdf/20250808/{uuid}/{filename}"

# 用户提供的UUID
given_uuids = [
    "84519de1-8bb4-4bd1-b3fa-e610b20d4408",
    "50b9bf1c-287f-4a58-baa9-071f2db350a6",
    "5df60712-8a75-4581-814e-16a203dd27bb"
]

# 为解决SSL问题，创建一个不验证SSL证书的上下文
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

# 不同的HTTP请求头
user_agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59"
]

def download_pdf(url, headers):
    """尝试下载PDF文件"""
    try:
        print(f"尝试URL: {url}")
        req = urllib.request.Request(url, headers=headers)
        
        # 设置超时时间为10秒，并使用自定义SSL上下文
        with urllib.request.urlopen(req, timeout=10, context=ssl_context) as response:
            # 检查响应状态码
            if response.status == 200:
                # 检查Content-Type是否为PDF
                content_type = response.getheader('Content-Type')
                if content_type and 'pdf' in content_type.lower():
                    # 读取并写入文件
                    data = response.read()
                    with open(pdf_save_path, 'wb') as out_file:
                        out_file.write(data)
                    
                    # 验证文件大小
                    if os.path.exists(pdf_save_path):
                        file_size = os.path.getsize(pdf_save_path)
                        if file_size > 100:  # 确保文件不为空
                            return True, file_size
                        else:
                            print(f"警告: 下载的文件可能是空的 (大小: {file_size} 字节)")
                            os.remove(pdf_save_path)
                            return False, 0
                else:
                    print(f"警告: 响应内容不是PDF文件 (Content-Type: {content_type})")
                    return False, 0
            else:
                print(f"HTTP错误: {response.status}")
                return False, 0
    except Exception as e:
        print(f"请求错误: {str(e)}")
        return False, 0

def main():
    print(f"开始尝试下载'{pdf_filename}'")
    print(f"保存路径: {pdf_save_path}")
    print(f"使用用户提供的UUID数量: {len(given_uuids)}")
    print(f"使用的URL模板: {base_url_template}")
    
    start_time = time.time()
    total_attempts = 0
    success = False
    
    # 尝试所有用户提供的UUID
    for uuid in given_uuids:
        if success:
            break
            
        # 随机选择用户代理
        headers = {'User-Agent': user_agents[total_attempts % len(user_agents)]}
        
        # 编码文件名
        encoded_filename = urllib.parse.quote(pdf_filename)
        # 构建完整URL
        url = base_url_template.format(uuid=uuid, filename=encoded_filename)
        
        # 下载PDF
        total_attempts += 1
        success, file_size = download_pdf(url, headers)
        
        # 如果成功，退出循环
        if success:
            print(f"\nPDF文件下载成功！")
            print(f"保存路径: {pdf_save_path}")
            print(f"文件大小: {file_size / 1024:.2f} KB")
            print(f"使用的UUID: {uuid}")
            print(f"使用的请求头: {headers}")
            break
        
        # 延迟2秒，避免请求过于频繁
        time.sleep(2)
    
    end_time = time.time()
    
    if not success:
        print(f"\n所有URL尝试都失败了。")
        print(f"总共尝试了 {total_attempts} 个URL组合")
        print(f"可能的原因:")
        print("1. 文件可能不存在或已被移动")
        print("2. 服务器可能限制了访问权限")
        print("3. 需要的UUID可能不是这三个中的任何一个")
        print("4. 文件名可能与预期不同")
        print("\n建议获取包含此PDF链接的HTML文件，或者确认文件是否存在于服务器上。")
    
    print(f"总耗时: {end_time - start_time:.2f} 秒")

if __name__ == "__main__":
    main()